﻿using System.IO.Compression;
using LibGit2Sharp;

static string GetMaskedPassword()
{
    string password = "";

    while (true)
    {
        ConsoleKeyInfo key = Console.ReadKey(true);
        if (key.Key == ConsoleKey.Enter)
        {
            Console.WriteLine();
            return password;
        }
        else if (key.Key == ConsoleKey.Backspace)
        {
            if (password.Length > 0)
            {
                password = password.Remove(password.Length - 1);
                Console.Write("\b \b");
            }
        }
        else
        {
            password += key.KeyChar;
        }
    }
}

if (args.Length == 1)
{
    if (args[0] == "createi")
    {
        Console.Write("Please Input EI Name:");
        string ein = Console.ReadLine();
        Directory.CreateDirectory(Path.Join(Environment.CurrentDirectory, ein));
        Directory.CreateDirectory(Path.Join(Environment.CurrentDirectory, Path.Join(ein, "ei")));
        File.Create(Path.Join(Environment.CurrentDirectory, Path.Join(ein, Path.Join("ei", "data.json"))));
        File.WriteAllText(Path.Join(Environment.CurrentDirectory, Path.Join(ein, Path.Join("ei", "data.json"))),
@"{
  ""exculable"": """",
  ""argument"": """",
  ""path"": true
}");
        Directory.CreateDirectory(Path.Join(Environment.CurrentDirectory, Path.Join(ein, "bin")));
        Console.WriteLine("Create Sucessfully");
    }
    else if (args[0] == "package")
    {
        Console.Write("Please Input EI Folder Path:");
        string ein = Console.ReadLine();
        ZipFile.CreateFromDirectory(ein, Path.Join(Environment.CurrentDirectory, ein + ".ei"), CompressionLevel.Optimal, false);
        Console.WriteLine("Package Sucessfully, EI File Is In " + Environment.CurrentDirectory);
    }
    else if (args[0] == "release")
    {
        try
        {
            // 用户交互输入
            Console.Write("Please Input EI File Name:");
            string ein = Console.ReadLine();

            Console.Write("Please Input Your Gitcode User Name:");
            string gun = Console.ReadLine();

            Console.Write("Please Input Your Gitcode Password:");
            string gpw = GetMaskedPassword();

            Console.Write("Please Input Your Gitcode Email:");
            string gem = Console.ReadLine();

            // 创建认证凭据
            var credentials = new UsernamePasswordCredentials
            {
                Username = gun,
                Password = gpw
            };

            // 初始化仓库
            Repository.Init(Environment.CurrentDirectory);

            using (var repo = new Repository(Environment.CurrentDirectory))
            {
                // 验证文件存在
                if (!File.Exists(ein))
                {
                    throw new FileNotFoundException($"File not found: {ein}");
                }

                // 确保windows文件夹存在
                string windowsDir = Path.Combine(Environment.CurrentDirectory, "windows");
                Directory.CreateDirectory(windowsDir);

                // 复制文件到windows目录
                string destPath = Path.Combine(windowsDir, Path.GetFileName(ein));
                File.Copy(ein, destPath, overwrite: true);

                // 添加文件到暂存区
                Commands.Stage(repo, destPath);

                // 创建提交
                var author = new Signature(gun, gem, DateTimeOffset.Now);
                repo.Commit($"Add {Path.GetFileName(ein)} to windows folder", author, author);

                // 配置远程仓库
                var remote = repo.Network.Remotes["origin"];
                const string remoteUrl = "https://gitcode.com/fengfei1989/osi_repository.git";

                if (remote != null)
                {
                    repo.Network.Remotes.Update("origin", r => r.Url = remoteUrl);
                }
                else
                {
                    remote = repo.Network.Remotes.Add("origin", remoteUrl);
                }

                // 推送变更
                var options = new PushOptions
                {
                    CredentialsProvider = (url, user, cred) => credentials
                };

                repo.Network.Push(remote, @"refs/heads/master", options);
                Console.WriteLine("\nRelease Sucessfully");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"\nError: {ex.Message}");
        }
    }
    else if (args[0] == "install")
    {
        Console.Write("Please Input EI File Name:");
        string ein = Console.ReadLine();
        InstallerDownloader.cloneSoftWareInstaller(ein);
        InstallerRunner.runInstaller(ein);
    }
}